<template>
    <a-card :bordered="false">
        <div class="table-operator">
            
      <a-button @click="handleAdd" type="primary" v-has="'haseequimentdocumentPermission:add'" icon="plus">新增</a-button>
      <a-button v-show="record.id" @click="handleEdit(record)" type="primary" v-has="'haseequimentdocumentPermission:edit'" icon="edit">编辑</a-button>
      <a-popconfirm :title="'确定删除选中文档吗?'" @confirm="() => myhandleDelete(record.id)">
        <a-button v-show="record.id"  type="primary" v-has="'haseequimentdocumentPermission:del'" icon="delete">删除</a-button>
       </a-popconfirm>
      
      <!-- <a-button type="primary" icon="download" @click="handleExportXls('设备资料表')">导出</a-button> -->
      <!-- <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="importExcelUrl" @change="handleImportExcel">
        <a-button type="primary" icon="import">导入</a-button>
      </a-upload> -->
      <!-- 高级查询区域 -->
      <!-- <j-super-query :fieldList="superFieldList" ref="superQueryModal" @handleSuperQuery="handleSuperQuery"></j-super-query>
      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDel"><a-icon type="delete"/>删除</a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px"> 批量操作 <a-icon type="down" /></a-button>
      </a-dropdown> -->
    </div>
      <!-- 左侧文件树 -->
      <a-col :span="4" class="clName">
        <!-- <a-form-model-item label="文件上传" prop="fileList">
              <j-upload v-model="fileList"></j-upload>
        </a-form-model-item> -->
        <a-tree
          :treeData="treeData"
          :defaultExpandAll="defaultExpandAll"
          @select="this.onSelect"
          style="height: 500px;overflow-y: auto;"
        >
        </a-tree>
      </a-col>
      <!-- 中间面板 -->
      <a-col :span="2"/>
      <!--右侧缩略图-->
      <a-col :span="18">
        <a-spin tip="Loading..." :spinning="spinning">
          <div v-for="(file, key) in dataSource" :key="key">
            <a-row>
              <a-col :span="24"><p><a-divider orientation="left">{{ file.fileName }}</a-divider></p></a-col>
              <!-- 预览区域 -->
              <a-col :span="24">
                <template v-if="file.filePdfPath">
                  <div style="float: left;width:104px;height:104px;margin-right: 10px;margin: 0 8px 8px 0;">
                    <div style="width: 100%;height: 100%;position: relative;padding: 8px;" @click="pdfPreview(file.filePdfPath)">
                      <img style="width: 100%;" src="~@/assets/pdf4.jpg">
                    </div>
                  </div>
                </template>
                <template v-else>
                  (暂无材料，点击"选择文件"或"扫描上传"上传文件)
                </template>
              </a-col>
            </a-row>
          </div>
        </a-spin>
      </a-col>
      <pdf-preview-modal ref="pdfmodal"></pdf-preview-modal >
        <yks-equipment-document-modal ref="modalForm" @ok="modalFormOk"></yks-equipment-document-modal>
    </a-card>
</template>
  
  <script>
  
    import { getAction,httpAction } from '@/api/manage'
    import { ACCESS_TOKEN } from "@/store/mutation-types"
    import Vue from 'vue'
    import PdfPreviewModal from './modules/YksEquipmentDocumentPdfPreviewModal'
    import { mixinDevice } from '@/utils/mixin'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import YksEquipmentDocumentModal from './modules/YksEquipmentDocumentModal'
import { validateDuplicateValue,randomUUID } from '@/utils/util'

    const mockdata=[{
      "id": "1",
      "key": "1",
      "title": "实例.pdf",
      "fileCode": "shili",
      "fileName": "实例",
      "filePdfPath": "实例"
    }]
  
    export default {
      name: "YksEquipmentDocumentList",
      mixins:[JeecgListMixin,mixinDevice],
      components:{
    PdfPreviewModal,
    YksEquipmentDocumentModal
},
      data () {
        return {
          description: '设备资料PDF预览页面',
          // 文件类型集
          treeData:[{
            title: '所有PDF电子档',
            key: '0-0',
            children: [] }],
          // 文件数据集
          dataSource: mockdata,
          allData:mockdata,
          // 上传文件集
          defaultExpandAll: true,
          // 加载中
          spinning:false,
          // 表头
        columns: [
          {
            title: '#',
            dataIndex: '',
            key:'rowIndex',
            width:60,
            align:"center",
            customRender:function (t,r,index) {
              return parseInt(index)+1;
            }
          },
          {
            title:'资料类别',
            align:"center",
            dataIndex: 'documentType_dictText'
          },
          {
            title:'名称',
            align:"center",
            dataIndex: 'documentName'
          },
          {
            title:'链接',
            align:"center",
            dataIndex: 'documentUrl'
          },
          {
            title:'值',
            align:"center",
            dataIndex: 'documentValue'
          },
          {
            title: '操作',
            dataIndex: 'action',
            align:"center",
            fixed:"right",
            width:147,
            scopedSlots: { customRender: 'action' }
          }
        ],
          url: {
            pdfList: "/mock/api/pdfList",
            list: "/mng/yksEquipmentDocument/list",
            delete: "/mng/yksEquipmentDocument/delete",
            edit: "/mng/yksEquipmentDocument/edit",
          },
          model:'',
          fileList:[],
          currentEquipmentId:'',
          categorys:[],
          records:[],
          record:{}
        }
      },
      created() {
        
        this.getSuperFieldList()

        console.log('created')
        
      },
      methods: {
        myhandleDelete(id){
          if(this.record.documentUrl){

            let files=JSON.parse(this.record.documentUrl)
            if(files.length==1){
              this.handleDelete(id)
            }
            else{
              if(this.dataSource[0].fileName){
                for(var i=0;i<files.length;i++){
                  if(files[i].key=="temp/"+this.dataSource[0].fileName){
                    files.splice(i,1)
                  }
                }
                
                this.record.documentUrl=JSON.stringify(files)
                this.updateFiles()
              }
            }
          }
        },
        updateFiles(){
          if (true) {
              let httpurl = '';
              let method = '';
                httpurl+=this.url.edit;
                 method = 'put';
                httpAction(httpurl,this.record,method).then((res)=>{
                if(res.success){
                  this.$message.success(res.message);
                  this.$emit('ok');
                  this.loadData(1)
                }else{
                  this.$message.warning(res.message);
                }
              }).finally(() => {
                this.confirmLoading = false;
              })
            }
        },
        open(record) {
        // this.model=record
        this.currentEquipmentId=record.id
        this.$refs.modalForm.currentEquipmentId=this.currentEquipmentId
        this.loadData()
        // console.log('open:'+JSON.parse(this) )
        // this.url.home=
      },
        loadData (){
            
          this.spinning = false;
          console.log('loadData')
          var params = this.getQueryParams();//查询条件
         params.equipmentId = this.currentEquipmentId
          getAction(this.url.list,params).then((res)=>{
            if (res.success) {
          //update-begin---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
          var result = res.result.records || res.result;
          this.records=result
        //   this.dataSource=[]
          var categoryList=[]
          for(var i=0;i<result.length;i++){
            var category=categoryList.find(p=>p.key==result[i].documentType)
            if(!category){
                category={
                    title:result[i].documentType_dictText,
                    key:result[i].documentType,
                    children:[]
                }
                categoryList.push(category)
            }
            
            if(category&&result[i].documentUrl){
                
                let files=JSON.parse(result[i].documentUrl) 
                for(var j=0;j<files.length;j++){
                    category.children.push({
                "id":result[i].id,
                "key":(i+1).toString()+"-"+j.toString(),
                "title": files[j].key.replace("temp/","").replace(".pdf",""),
                "fileCode": files[j].key,
                "fileName": files[j].key.replace("temp/",""),
                "filePdfPath": files[j].url
            })
                }
                
            }
            

          }
          this.categorys=categoryList
          this.treeData[0].children=this.categorys
          this.allData=this.categorys
          this.dataSource=this.categorys
          //update-end---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
        } 
            // if(res.length>0){
               
            // //   this.allData = res;
            // //   this.dataSource = res;
            // //   this.treeData[0].children = res;
            // }
            this.spinning = false;
          })
        },
        pdfPreview:function(title){
          const token = Vue.ls.get(ACCESS_TOKEN);
          this.headers = {"X-Access-Token":token}
          this.$refs.pdfmodal.previewFiles(title,token);
        },
        // 选择文件类型
        onSelect (selectedKeys, info) {
          this.dataSource = [];
          if(selectedKeys[0] === undefined || selectedKeys[0] === '0-0'){
            this.dataSource = this.allData;
          }else{
            this.dataSource.push(info.node._props.dataRef);
          }
          if(this.dataSource[0].id){
            this.record=this.records.find(p=>p.id==this.dataSource[0].id)
          }else{
            this.record={}
          }
          console.log("SELECT-->dataSource",this.dataSource );
        },
        // model回调
        modalFormOk () {
          this.loadData();
        },
        getSuperFieldList(){
        let fieldList=[];
        fieldList.push({type:'string',value:'documentType',text:'资料类别',dictCode:'document _type'})
        fieldList.push({type:'string',value:'documentName',text:'名称',dictCode:''})
        fieldList.push({type:'string',value:'documentUrl',text:'链接',dictCode:''})
        fieldList.push({type:'string',value:'documentValue',text:'值',dictCode:''})
        this.superFieldList = fieldList
      }
      },
    }
  </script>
  
  <style scoped>
    .clName .ant-tree li span.ant-tree-switcher, .ant-tree li span.ant-tree-iconEle{width:10px}
  </style>